package com.cinema.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.model.entity.Poster;
import com.cinema.api.model.entity.User;
import com.cinema.api.mapper.UserMapper;
import com.cinema.api.model.enums.ResultCodeEnum;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.model.vo.FilmVO;
import com.cinema.api.model.vo.LoginVO;
import com.cinema.api.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import com.cinema.api.utils.DataTimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 获取登录用户信息
     * @param loginVO
     * @return
     */
    @Override
    public User getLogin(LoginVO loginVO) throws Exception {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("username", loginVO.getUsername())
                .eq("is_delete", 0);
        User user = userMapper.selectOne(wrapper);
        if (BaseUtil.isEmpty(user)) {
            throw new BizException(ResultCodeEnum.USERNAME_PASSWORD_NOT_FOUND);
        }
        if (!bCryptPasswordEncoder.matches(loginVO.getPassword(), user.getPassword())) {
            throw new BizException(ResultCodeEnum.USERNAME_PASSWORD_NOT_FOUND);
        }
        return user;
    }

    /**
     *  返回所有用户信息
     */
    @Override
    public List<User> findAll() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        return userMapper.selectList(wrapper);
    }

    /**
     *  更新用户信息
     */
    @Override
    public void updateUser(User user) {
        // 对密码进行加密换算
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setUpdateTime(DataTimeUtil.getNowTimeString());
        userMapper.updateById(user);
    }

    /**
     *  用户注册
     */
    @Override
    public void register(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("phone", user.getPhone())
                .eq("is_delete", 0);
        if (BaseUtil.isNotEmpty(userMapper.selectOne(wrapper))) {
            throw new BizException(1001, "该手机号码已被占用");
        }
        if (findByUserName(user.getUsername()) != null) {
            throw new BizException(1001, "用户名已被注册");
        }
        user.setId(UUID.randomUUID().toString());
        user.setCreateTime(DataTimeUtil.getNowTimeString());
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setIsDelete(0);
        userMapper.insert(user);
    }

    /**
     *  分页返回用户列表
     */
    @Override
    public PageInfo<User> findAllByPage(int page, int limit) {
        // 使用Mybatis分页插件
        PageHelper.startPage(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        List<User> users = userMapper.selectList(wrapper);
        return new PageInfo<>(users);
    }

    /**
     * 根据用户名模糊查询
     */
    @Override
    public PageInfo<User> findByLike(int page, int limit, String username) {
        // 使用Mybatis分页插件
        PageHelper.startPage(page, limit);
        List<User> like = userMapper.findByLike(username);
        return new PageInfo<>(like);
    }


    /**
     * 根据用户名查找用户
     */
    @Override
    public User findByUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("username", username)
                .eq("is_delete", 0);
        return userMapper.selectOne(wrapper);
    }

    /**
     * 根据用户名以及电话查找用户
     */
    @Override
    public User findByNameAndPhone(String username, String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("username", username)
                .in("phone", phone)
                .eq("is_delete", 0);
        User user= userMapper.selectOne(wrapper);
        return user;
    }

    /**
     * 根据用户名更新用户信息
     */
    @Override
    public void reset(String username, String password) {
        User user = findByUserName(username);
        user.setPassword(bCryptPasswordEncoder.encode(password));
        user.setUpdateTime(DataTimeUtil.getNowTimeString());
        userMapper.updateById(user);
    }

    /**
     * 根据Id查找用户
     */
    @Override
    public User findById(String id) {
        return userMapper.selectById(id);
    }

    /**
     * 用户更新身份信息
     */
    @Override
    public void updateBySelf(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("phone", user.getPhone())
                .ne("id", user.getId())
                .eq("is_delete", 0);
        if (BaseUtil.isNotEmpty(userMapper.selectOne(wrapper))) {
            throw new BizException(1001, "该手机号码已被占用");
        }
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setUpdateTime(DataTimeUtil.getNowTimeString());
        userMapper.updateById(user);
    }


    /**
     *  单元测试
     */
    public static void main(String[] args) {
        String password = "123456";
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        System.out.println(encode);
        boolean matches = bCryptPasswordEncoder.matches("123456", "$2a$10$Tga6WzIixFpRNgqDhq7y1OUbjFApiv/3AlyBsS80qff2pPmNZJsuK");
        System.out.println(matches);
    }
}
